package leetcode.code0792;

import java.util.LinkedList;
import java.util.Queue;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution2 implements IDebug {

	class Node {
		Node[] me;
		int cnt;

		public Node() {
			me = new Node[26];
		}

		public void add(String word) {
			Node node = this;
			char[] cs = word.toCharArray();
			for (int i = 0; i < cs.length; i++) {
				int c = cs[i] - 'a';
				if (node.me[c] == null) {
					node.me[c] = new Node();
				}
				node = node.me[c];
			}
			node.cnt += 1;
		}
	}

	public int numMatchingSubseq(String s, String[] words) {
		Node root = new Node();
		for (String word : words) {
			root.add(word);
		}
		Queue<Node>[] match = new LinkedList[26];
		for (int i = 0; i < match.length; i++) {
			match[i] = new LinkedList<>();
		}
		this.addMatch(match, root);
		char[] cs = s.toCharArray();
		int ans = 0;
		for (int i = 0; i < cs.length; i++) {
			int c = cs[i] - 'a';
			Queue<Node> queue = match[c];
			int size = queue.size();
			while (size > 0) {
				Node cur = queue.poll();
				ans += cur.cnt;
				this.addMatch(match, cur);
				size--;
			}
		}
		return ans;
	}

	private void addMatch(Queue<Node>[] match, Node root) {
		Node cur = null;
		for (int i = 0; i < 26; i++) {
			if ((cur = root.me[i]) != null) {
				match[i].add(cur);
			}
		}
	}

	@Override
	public void debug4() {
		H.compare(1, this.numMatchingSubseq("dcaog", H.str2array2("[\"cop\",\"dog\",\"cat\"]")));
		H.compare(3, this.numMatchingSubseq("abcde", H.str2array2("[\"a\",\"bb\",\"acd\",\"ace\"]")));
		H.compare(2, this.numMatchingSubseq("dsahjpjauf",
				H.str2array2("[\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
